//
//  QuaternionRotation.m
//  NinevehglTest
//
//  Created by 郝建林 on 2016/10/18.
//  Copyright © 2016年 CoolTools. All rights reserved.
//

#import "QuaternionRotation.h"

@interface QuaternionRotation()
{
    NGLQuaternion *quaternion;
    float qw, qx, qy, qz;
}
@end

@implementation QuaternionRotation

@synthesize view;

- (id)init {
    if(self = [super init]) {
        quaternion = [[NGLQuaternion alloc] init];
        qw = 1;
        qx = 0;
        qy = 0;
        qz = 0;
        [self updateQuternioin];
    }
    return self;
}

- (float)rx {
    return quaternion.euler.x;
}

- (float)ry {
    return quaternion.euler.y;
}

- (float)rz {
    return quaternion.euler.z;
}

- (void)setRx:(float)rx {

}

- (void)setRy:(float)ry {

}

- (void)setRz:(float)rz {

}

- (void)reset {
    qw = 1;
    qx = 0;
    qy = 0;
    qz = 0;
    [self updateQuternioin];
    [self updateSlider:SliderW ofValue:qw];
    [self updateLabel:SliderW ofValue:qw];
    [self updateSlider:SliderX ofValue:qx];
    [self updateLabel:SliderX ofValue:qx];
    [self updateSlider:SliderY ofValue:qy];
    [self updateLabel:SliderY ofValue:qy];
    [self updateSlider:SliderZ ofValue:qz];
    [self updateLabel:SliderZ ofValue:qz];
}

- (void)onSliderChanged: (NSInteger)sliderIndex value: (float)sliderValue {
    float ratio = [self ratioOfSliderValue:sliderValue];
    //update value
    switch(sliderIndex) {
        case SliderW:
            qw = ratio;
            break;
        case SliderX:
            qx = ratio;
            break;
        case SliderY:
            qy = ratio;
            break;
        case SliderZ:
            qz = ratio;
            break;
    }
    [self updateQuternioin];
    //update label
    [self updateLabel:sliderIndex ofValue:ratio];
}

- (float)ratioOfSliderValue: (float)sliderValue {
    return sliderValue * 2 - 1;
}

- (void)updateSlider: (NSInteger)index ofValue: (float)value
{
    UISlider *slider = [self.view viewWithTag:SliderTagBase+index];
    slider.value = (value + 1) / 2;
}

- (void)updateLabel: (NSInteger)index ofValue: (float)value
{
    UILabel *label = (UILabel*)[self.view viewWithTag:index+LabelTagBase];
    label.text = [NSString stringWithFormat:@"%.2f", value];
}

- (void)updateQuternioin
{
    [quaternion rotateByQuaternionVector:nglVec4Make(qx, qy, qz, qw) mode:NGLAddModeSet];
}

@end
